//
//  RootViewController.m
//  danpin
//
//  Created by chuangjia on 28/7/15.
//  Copyright (c) 2015 chuangjia. All rights reserved.
//

#import "RootViewController.h"
#import "UINavigationController+YRBackGesture.h"
#import "viewconfig.h"
#import "BaseCell.h"
#import "UserRegisterNameVC.h"
#import "UserLoginVC.h"
#import "ProductLinkVC.h"
#import "ShaiDanVC.h"
#import "UserNavigationController.h"

#import "ShareorderConfig.h"
#import "UserConfig.h"
#import "messageconfig.h"
#import "UMengShare.h"
#import "SlidingViewManager.h"

#import "niubiConfig.h"

#import "WKPopBuyView.h"
#import "storageconf.h"
#import "ZPlatformShare.h"
#import "CMPopTipView.h"
#import "WKPopView.h"
#import "WebViewController.h"
#import "ZSpotLightHelper.h"
//#define SELECTED_VIEW_CONTROLLER_TAG 98456345

static RootViewController *rootViewController;
@implementation UIViewController (RootViewControllerSupport)

- (RootViewController *)rootViewController
{
    return rootViewController;
}

@end

@interface RootViewController ()<UserDelegate,RKTabViewDelegate>
{
    
}
@property(nonatomic,strong) UIView* currentView; 

@property(nonatomic,strong)NiubiViewController *niubiVC;
@property(nonatomic,strong)ShaiorderViewController *rankVC;
@property(nonatomic,strong)StorageIndexViewController *chatVC;
@property(nonatomic,strong)UserViewController *userVC;
//
@property(nonatomic,strong)ProductLinkVC *productlinkVC;
//
@property(nonatomic,strong)UIViewController *currentViewController;
@property(nonatomic,strong)UINavigationController *currentNav;
@property(nonatomic,assign)NSInteger currentIndex;
@property(nonatomic,assign)NSInteger oldIndex;
@property(nonatomic,strong)UIImageView *dotMassageView;
@property(nonatomic,strong)UIImageView *dotMassageView1;
@property(nonatomic,strong)SlidingViewManager *svm;
//
@property(nonatomic,strong)CMPopTipView *popTipView;
@end

@implementation RootViewController
@synthesize dotMassageView=_dotMassageView;
@synthesize dotMassageView1=_dotMassageView1;
@synthesize popTipView=_popTipView;
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    rootViewController=self;
    _currentIndex=0;
    _oldIndex = 0;

    [self initTabBarView];
    [self dotMessage:@"Root"];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(applicationWillEnterForeground)
                                                 name:UIApplicationWillEnterForegroundNotification
                                               object:[UIApplication sharedApplication]];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(loginOut)
                                                 name:@"loginout"
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(updatebadge)
                                                 name:@"updatebadge"
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(updateHuobadge)
                                                 name:@"updateHuobadge"
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(shareToBuy)
                                                 name:@"shareToBuy"
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(ShowShaiDanSuccess:) name:@"shaidanok" object:nil];
  
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationSlide];
}
- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleDefault;
}


- (void) refreshBaoliao
{
    if(_niubiVC)
    {
        [_niubiVC refreshBaoliao];
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
      DLog(@"%s", __PRETTY_FUNCTION__);
}
-(void)dealloc
{
    self.svm=nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    DLog(@"%s", __PRETTY_FUNCTION__);
}


-(void)initTabBarView
{
    RKTabItem *homeTabItem = [RKTabItem createUsualItemWithImageEnabled:[UIImage imageNamed:@"nav_home_selected"] imageDisabled:[UIImage imageNamed:@"nav_home_normal"]];
    homeTabItem.titleString = @"推荐";
    homeTabItem.tabState =TabStateEnabled;
    RKTabItem *findTabItem = [RKTabItem createUsualItemWithImageEnabled:[UIImage imageNamed:@"nav_show_selected"] imageDisabled:[UIImage imageNamed:@"nav_show_normal"]];
    findTabItem.titleString = @"发现";
    RKTabItem *qiuTabItem = [RKTabItem createUsualItemWithImageEnabled:[UIImage imageNamed:@"nav_plus"] imageDisabled:[UIImage imageNamed:@"nav_plus"]];
    qiuTabItem.titleString = @"";
    RKTabItem *messageTabItem = [RKTabItem createUsualItemWithImageEnabled:[UIImage imageNamed:@"nav_message_selected"] imageDisabled:[UIImage imageNamed:@"nav_message_normal"]];
    messageTabItem.titleString = @"尖货";
    RKTabItem *myTabItem = [RKTabItem createUsualItemWithImageEnabled:[UIImage imageNamed:@"nav_mine_selected"] imageDisabled:[UIImage imageNamed:@"nav_mine_normal"]];
    myTabItem.titleString = @"我的";
    if (self.tabbar) {
        self.tabbar.tabItems=nil;
        self.tabbar.delegate=nil;
        [self.tabbar removeFromSuperview];
        self.tabbar=nil;
    }
    _tabbar = [[RKTabView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height-hightAuto(45), self.view.bounds.size.width,hightAuto(45))];
    _tabbar.backgroundColor = DARK_BACKGROUND_COLOR;//UIColorFromRGB(0x010101);
    _tabbar.delegate=self;
    [self.view addSubview:_tabbar];
    
    [_tabbar setHidden:NO];
     _tabbar.tabItems = @[homeTabItem, findTabItem, qiuTabItem, messageTabItem, myTabItem];
    [self touchBtnAtIndex:0 isTop:NO];
}
-(void)loginOut
{
    if (_niubiVC) {
        [_niubiVC removeFromParentViewController];
        _niubiVC =nil;

    }
    if (_rankVC) {
        [_rankVC removeFromParentViewController];
        _rankVC =nil;
    }
    if (_chatVC) {
        [_chatVC removeFromParentViewController];
        _chatVC =nil;
    }
    if (_userVC) {
        [_userVC removeFromParentViewController];
        _userVC =nil;
    }
    if(_currentView)
    {
        [_currentView removeFromSuperview];
        _currentView=nil;
    }
    
//    [self touchBtnAtIndex:0 isTop:NO];
    self.tabbar.selectedIndex =0;
}

-(void)touchBtnAtIndex:(NSInteger)index isTop:(BOOL)isTop
{

    _currentIndex = index;
    
    if(_currentView)
    {
       // UIView* currentView = [self.view viewWithTag:SELECTED_VIEW_CONTROLLER_TAG];
        [_currentView removeFromSuperview];
       // _currentView.hidden = YES;
        _currentView=nil;
    }

    switch (index) {
        case 0:
        {
            
            if (!_niubiVC)
            {
                _niubiVC =[[NiubiViewController alloc] init];
                
            }
            if (isTop)
            {
                [_niubiVC scrollToTop];
            }
            else
            {
                if(_currentViewController == _niubiVC)
                {
                    [_niubiVC scrollToTop];
                }
            }
            _oldIndex=0;
            _currentViewController = _niubiVC;
            _currentView = _niubiVC.view;
            
            
            [self dotMessage:@"indexTab"];
        }
            break;
        case 1:
        {
           
            if (!_rankVC) {
                _rankVC =[[ShaiorderViewController alloc] init];
                
                //_rankVC.view.tag =SELECTED_VIEW_CONTROLLER_TAG;
            }
            if (isTop) {
                [_rankVC scrollToTop];
            }
            else
            {
                if(_currentViewController == _rankVC)
                {
                    [_rankVC scrollToTop];
                }
            }
            
            _oldIndex=1;
            _currentViewController = _rankVC;
            _currentView = _rankVC.view;
          
            [self dotMessage:@"shaidanTab"];
        }
            break;

        case 2:
        {
        }
            break;
        case 3:
        {
            _currentIndex = index;
            
            if (!_chatVC) {
                _chatVC =[[StorageIndexViewController alloc] init];
            }
           
            if (isTop) {
                [_chatVC scrollToTop];
            }
            else
            {
                if(_currentViewController == _chatVC)
                {
                    [_chatVC scrollToTop];
                }
            }
            _oldIndex=3;
            _currentViewController = _chatVC;
            _currentView = _chatVC.view;
            
            [self dotMessage:@"messageTab"];
            //有新数据时刷新数据
            if([UIApplication sharedApplication].applicationIconBadgeNumber>0&&_dotMassageView1)
            {
                [_chatVC reloadData];
            }
            if (_dotMassageView1) {
                [_dotMassageView1 removeFromSuperview];
                _dotMassageView1=nil;
            }
        }
            break;
        case 4:
        {
            if ([self isLogin]) {
                if (!_userVC) {
                    _userVC =[[UserViewController alloc] init];
                    _userVC.isMe=YES;
                    if([UIApplication sharedApplication].applicationIconBadgeNumber>0||_dotMassageView)
                    {
                        _userVC.isMessage = YES;
                    }
    
                }
                [_userVC reloadData];
                
                if (isTop) {
                    [_userVC scrollToTop];
                }
                else
                {
                    if(_currentViewController == _userVC)
                    {
                        [_userVC scrollToTop];
                    }
                }
                
                _oldIndex=4;
        
                _currentViewController = _userVC;
                _currentView = _userVC.view;
            
                [self dotMessage:@"userTab"];
                
            }else{
                return;
            }
        }
            break;
        
        default:
            break;
    }
    _currentViewController.view.frame = CGRectMake(0,0,self.view.frame.size.width, self.view.frame.size.height);
    if (_currentNav) {
        [_currentNav removeFromParentViewController];
        _currentNav =nil;
    }
    _currentNav =[[UINavigationController alloc] initWithRootViewController:_currentViewController];
    [_currentNav setEnableBackGesture:YES];
    _currentNav.navigationBarHidden =YES;
    [self.view insertSubview:_currentNav.view belowSubview:_tabbar];
    
    if([UIApplication sharedApplication].applicationIconBadgeNumber>0)
    {
        [self updatebadge];
    }
}
-(UIImageView*)dotMassageView
{
    if (_dotMassageView) {
        [_dotMassageView removeFromSuperview];
        _dotMassageView=nil;
    }
    _dotMassageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"new_message_tip"]];
    if (IS_IPHONE_6P) {
        _dotMassageView.frame=CGRectMake(DEVICE_WIDTH-40, 5, 10, 10);
    }else if (IS_IPHONE_6){
        _dotMassageView.frame=CGRectMake(DEVICE_WIDTH-35, 5, 10, 10);
    }else{
        _dotMassageView.frame=CGRectMake(DEVICE_WIDTH-30, 5, 10, 10);
    }
    return _dotMassageView;
}
-(void)updateHuobadge
{
    if (_tabbar) {
        [_tabbar addSubview:self.dotMassageView1];
    }
}
-(UIImageView*)dotMassageView1
{
    if (_dotMassageView1) {
        [_dotMassageView1 removeFromSuperview];
        _dotMassageView1=nil;
    }
    _dotMassageView1 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"new_message_tip"]];
    if (IS_IPHONE_6P) {
        _dotMassageView1.frame=CGRectMake(DEVICE_WIDTH-120, 5, 10, 10);
    }else if (IS_IPHONE_6){
        _dotMassageView1.frame=CGRectMake(DEVICE_WIDTH-110, 5, 10, 10);
    }else{
        _dotMassageView1.frame=CGRectMake(DEVICE_WIDTH-95, 5, 10, 10);
    }
    
    return _dotMassageView1;
}
-(BOOL)isLogin
{
    if ([[ZShare sharedInstance] isLogin]) {
        return YES;
    }else
    {
        UserNavigationController *viewcontroller =[UserNavigationController newWithCameraDelegate:self];
        [self presentViewController:viewcontroller animated:NO completion:nil];
        
        return NO;
    }
    return NO;
}
-(void)userLoginOK:(id)userinfo
{
    [self dismissViewControllerAnimated:YES completion:nil];
    if(_currentIndex==2)
    {
        return ;
    }
    [self touchBtnAtIndex:_currentIndex isTop:NO];
   
}
-(void)userDidCancel
{
    [self touchBtnAtIndex:_oldIndex isTop:NO];
    self.tabbar.selectedIndex =_oldIndex;
    [self dismissViewControllerAnimated:YES completion:nil];
}
-(void)updatebadge
{
    if (_tabbar) {
        [_tabbar addSubview:self.dotMassageView];
    }
}
-(void)removeDotmessage
{
    if (_dotMassageView) {
        [_dotMassageView removeFromSuperview];
        _dotMassageView=nil;
    }
}

-(void)applicationWillEnterForeground
{
    [self dotMessage:@"enterforeground"];
}
-(void)dotMessage:(NSString*)source
{
//    [self showTipOfNewUser];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // this makes sure the change notification happens on the MAIN THREAD
        [[ZShare sharedInstance] initdanpinpublicparams:source];
        //
        [[ZSpotLightHelper helper] spotlightSearch:@""];
    });
}
#pragma mark - RKTabViewDelegate

- (void)tabView:(RKTabView *)tabView tabBecameEnabledAtIndex:(int)index tab:(RKTabItem *)tabItem {
//    NSLog(@"Tab № %d became enabled on tab view", index);
    if (index==2) {
    
        ShaiDanVC *shaidanVC =[[ShaiDanVC alloc] init];
        [self.navigationController pushViewController:shaidanVC animated:YES];
        shaidanVC=nil;
        return;
    }else{
         [self touchBtnAtIndex:index isTop:NO];
    }
   
    
}
-(void)tabView:(RKTabView *)tabView tabBecameDisabledAtIndex:(int)index tab:(RKTabItem *)tabItem
{
//       NSLog(@"Tab № %d became enabled on tab view", index);
}
-(void)showMenu
{
    UIView *notificationView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width,hightAuto(405))];
    notificationView.backgroundColor= [UIColor clearColor];
    UIImageView *bg =[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, notificationView.frame.size.width, notificationView.frame.size.height)];
    bg.image =[UIImage imageNamed:@"publish_bg.png"];
    [notificationView addSubview:bg];
    bg=nil;
    //
    UIButton *qiugou =[UIButton buttonWithType:UIButtonTypeCustom];
    qiugou.frame =CGRectMake(DEVICE_WIDTH/2-widthAuto(90)-PHOTO_FRAME_WIDTH*2, notificationView.frame.size.height-hightAuto(180)-10, widthAuto(90), hightAuto(90));
    qiugou.tag=0;
    [qiugou setImage:[UIImage imageNamed:@"publish_qg_normal.png"] forState:UIControlStateNormal];
    [qiugou setImage:[UIImage imageNamed:@"publish_qg_hover.png"] forState:UIControlStateSelected];
    [qiugou addTarget:self action:@selector(clickMenuView:) forControlEvents:UIControlEventTouchUpInside];
    [notificationView addSubview:qiugou];
    //
    UIButton *shaidan =[UIButton buttonWithType:UIButtonTypeCustom];
    shaidan.tag=1;
    shaidan.frame =CGRectMake(DEVICE_WIDTH/2+PHOTO_FRAME_WIDTH*2, notificationView.frame.size.height-hightAuto(180)-10, widthAuto(90), hightAuto(90));
    [shaidan setImage:[UIImage imageNamed:@"publish_sd_normal.png"] forState:UIControlStateNormal];
    [shaidan setImage:[UIImage imageNamed:@"publish_sd_hover.png"] forState:UIControlStateSelected];
     [shaidan addTarget:self action:@selector(clickMenuView:) forControlEvents:UIControlEventTouchUpInside];
    [notificationView addSubview:shaidan];
    //
    UIButton *close =[UIButton buttonWithType:UIButtonTypeCustom];
    close.frame =CGRectMake((DEVICE_WIDTH-widthAuto(30))/2, notificationView.frame.size.height-hightAuto(30)-10, widthAuto(30), hightAuto(30));
    close.tag=2;
    [close setImage:[UIImage imageNamed:@"publish_close.png"] forState:UIControlStateNormal];
    [close addTarget:self action:@selector(clickMenuView:) forControlEvents:UIControlEventTouchUpInside];
    [notificationView addSubview:close];
    
    if (self.svm) {
        self.svm=nil;
    }
    _svm = [[SlidingViewManager alloc] initWithInnerView:notificationView containerView:self.view];
    [_svm slideViewIn];
    
}
#pragma mark - CNPPopupController Delegate
-(void)clickMenuView:(id)sender
{
    UIButton *btn =(UIButton*)sender;
    switch (btn.tag) {
        case 0:
        {
            [self.svm slideViewOut];
          
        }
            break;
        case 1:
        {
            [self.svm slideViewOut];
            ShaiDanVC *shaidanVC =[[ShaiDanVC alloc] init];
            [self.navigationController pushViewController:shaidanVC animated:YES];
            shaidanVC=nil;
        }
            break;
        case 2:
        {
            [self.svm slideViewOut];
        }
            break;
        default:
            break;
    }
}
-(void)shareToBuy
{
//    [self shareToBuy:[ZShare sharedInstance].sharelist_key];
}
-(void)shareToBuy:(id)obj
{
    return;
    __block WKPopBuyView *popView=nil;
    popView=[WKPopBuyView showAlertViewWithTitle:@"" subTitle:@"" callBlock:^(WindowClick buttonIndex) {
        switch (buttonIndex) {
            case 0:
            {
                popView.hidden=YES;
                popView=nil;
            }
                break;
            case 1:
            {
                popView.hidden=YES;
                popView=nil;
            }
                break;
            default:
                break;
        }
    }];
}
- (void) showTipOfNewUser
{
    NSString *contentMessage = @"全球百万好货，\n官网发货，一键购买\n点此，开启剁手";
    UIColor *backgroundColor = COLOR_TAG_COMMENT;
    
    //[colorScheme objectAtIndex:0];
    UIColor *textColor = [UIColor whiteColor];
    
    if(_popTipView == nil)
        _popTipView = [[CMPopTipView alloc] initWithMessage:contentMessage] ;
    _popTipView.backgroundColor = backgroundColor;
    _popTipView.textColor = textColor;
    
    _popTipView.animation = arc4random() % 2;
    
    if(_popTipView.targetObject == nil){
        
        [_popTipView presentPointingAtView:_tabbar inView:self.view animated:YES];
   
    }
    
}
-(void)ShowShaiDanSuccess:(NSNotification *)notification
{
     NSDictionary *userInfo = notification.object;
    
    __block WKPopView *popView=nil;
    popView=[WKPopView showAlertViewWithTitle:@"晒单发布成功" subTitle:[[NSString stringWithFormat:@"%@",[userInfo objectForKey:@"msg"]] replaceNullString] callBlock:^(WindowClick1 buttonIndex) {
        switch (buttonIndex) {
            case 0:
            {
                popView.hidden=YES;
                popView=nil;
            }
                break;
            case 1:
            {
                popView.hidden=YES;
                popView=nil;
                ShaiorderDetailViewController *good =[[ShaiorderDetailViewController alloc] init];
                good.type =-1;
                good.dictionary = nil;
                good.photo_id = [NSString stringWithFormat:@"%@",[userInfo objectForKey:@"photo_id"]];
                [self.rootViewController.navigationController pushViewController:good animated:YES];
            }
                break;
            default:
                break;
        }
    }];
}
//推送事件
-(void)pushWebController:(NSString*)posturl
{
    
    WebViewController *shaidanweb =[[WebViewController alloc] init];
    shaidanweb.titlestr= @"push";
    shaidanweb.jsonUrl = posturl;
    shaidanweb.urlstr=@"";
    [self.navigationController pushViewController:shaidanweb animated:YES];
    shaidanweb=nil;
    return;
}
@end
